package com.fit.dao.card;

import java.util.Date;
import java.util.List;

import org.apache.tapestry5.annotations.Log;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.fit.entities.card.Card;
import com.fit.entities.typeofcard.TypeOfCard;

public class CardDAOImpl implements CardDAO{

	@Inject
	private Session session;

	@Log
	public boolean save(Card newCard) {
		if (newCard != null) {
			session.save(newCard);
			return true;
		}
		return false;
	}

	@Log
	public boolean delete(Card card) {
		if (card != null) {
			session.delete(card);
			return true;
		}
		return false;
	}

	@Log
	public boolean update(Card card) {
		if (card != null) {
			session.update(card);
			return true;
		}
		return false;
	}

	@Log
	public List findAll() {
		return session.createCriteria(Card.class).list();
	}

	@Log
	public boolean deleteByID(Long id) {
		Card u = findByID(id);
		if (u != null) {
			delete(u);
			return true;
		}
		return false;
	}

	@Log
	public Card findByID(Long id) {
		if (id != null) {
			return (Card) session.get(Card.class, id);
		}
		return null;
	}

	@Log
	public Card findByStartDate(Date startDate) {
		if (startDate == null) {
			return null;
		}

		

		List l = session.createCriteria(Card.class)
				.add(Restrictions.eq("start_date", startDate)).list();
				
		Card u = null;
		if (l != null) {
			if (l.size() > 0) {
				u = (Card) l.get(0);
			}
		}
		return u;
	}

	@Log
	public Card findByEspireDate(Date endDate) {
		if (endDate == null) {
			return null;
		}

		

		List l = session.createCriteria(Card.class)
				.add(Restrictions.eq("end_date", endDate)).list();
				
		Card u = null;
		if (l != null) {
			if (l.size() > 0) {
				u = (Card) l.get(0);
			}
		}
		return u;
	}

	public Card findByCardTypeId(Long id) {
		// TODO Auto-generated method stub
		return null;
	}

	public List<Card> findAllByTypeOfCard(TypeOfCard typeOfCard) {
		if (typeOfCard!=null) {
			return (List<Card>) session.createCriteria(Card.class).add(Restrictions.eq("card_type_id", typeOfCard.getId()));
		}
		return null;
		
	}

	
	

}
